package com.sapient.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sapient.logic.User;

/**
 * Servlet implementation class CreateUser
 */
@WebServlet("/CreateUser")
public class CreateUser extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CreateUser() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String username=request.getParameter("Username");
		String password=request.getParameter("Password");
		String[] userRole= request.getParameterValues("role");
		PrintWriter pw=response.getWriter();
		User newUser= new User(username,password,userRole[0]);
		boolean userExists=false;
		
		try {
			userExists=newUser.createUser();
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		if(userExists){
			request.getRequestDispatcher("/CreateUser.jsp").include(request, response);  
			pw.write("<p align='left' style ='color:Red'><b>Username already exists</b></p>");
			pw.write("<br>");

		}	
		else{
			request.getRequestDispatcher("/Home.jsp").include(request, response);
			pw.write("<p align='left' style ='color:Red'><b>User Succesfully Created</b></p>");
			pw.write("<br>");
		}
		

	}

}
